package org.artifact.core.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.setting.Setting;
import lombok.Builder;

/**
 * 生成protobuff代码
 * @author apple
 *
 */
@Builder
public class ProtoUtil {
	/** proto文件路径 */
	private String inputPath;

	/** 生成的java文件路径 */
	private String outputPath;

	/** protoc.exe 路径 */
	private String exeFile;

	public void exec(){
		if (StrUtil.isBlank(inputPath) || StrUtil.isBlank(outputPath) || StrUtil.isBlank(exeFile)) {
			throw new IllegalStateException("请检查配置");
		}
		
		File protoBack = new File("proto.back");
		Setting setting = null;
		if(FileUtil.isFile(protoBack)){
			setting = new Setting(protoBack,Charset.forName("UTF-8"),false);
		}
		
		final Setting setting2 = setting;
		List<String> list = new ArrayList<>();
		list.add("##################### Date:" + DateUtil.now()+"#####################");
		List<File> protos = FileUtil.loopFiles(inputPath, new FileFilter() {
			@Override
			public boolean accept(File file) {
				
				if (FileUtil.pathEndsWith(file, ".proto")) {
					String md5 = SecureUtil.md5(FileUtil.readString(file, "UTF-8"));
					String val = file.getName() + "=" + md5;
					list.add(val);
					
					if (setting2 != null && md5.equals(setting2.getStr(file.getName()))) {
						return false;
					}else {
						return true;
					}
				}
				return false;
			}
		});

		FileUtil.writeLines(list, protoBack, "UTF-8");
		
		for (File file : protos) {
			String command = String.format("%s -I=%s --java_out=%s %s ", exeFile, inputPath, outputPath,file.getPath());
			try {
				Runtime.getRuntime().exec(command);
				System.out.println(command);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
